#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef double db;

#define in read()
#define pii pair<int,int>
#define fi first
#define se second
#define FILE(x) freopen(x".in","r",stdin);\
	freopen(x".out","w",stdout);
#define pb push_back

int read(){
	int x = 0,sgn = 1;char ch = getchar();
	for(;!isdigit(ch);ch = getchar()) if(ch == '-') sgn = -1;
	for(;isdigit(ch);ch = getchar()) x = (x<<1)+(x<<3)+(ch^48);
	return x*sgn;
}

const int N = 1e5+10;

int fa[22][N],dep[N],n,rt[N],ans[N],val[N<<6],ls[N<<6],rs[N<<6],cnt,m;
vector<int> G[N];
vector<pii> que[N];

void dfs(int x){
	dep[x] = dep[fa[0][x]] + 1;
	for(int y : G[x]) dfs(y);
}

int kanc(int x,int k){
	for(int i = 20;i >= 0;i--)
		if(k >> i & 1) x = fa[i][x];
	return x;
}

void merge(int &y,int x,int l = 1,int r = n){
	if(!y || !x) return y = x + y,void(); int mid = l + r >> 1;
 	val[y] = val[x] + val[y]; merge(ls[y],ls[x],l,mid); merge(rs[y],rs[x],mid + 1,r);
}

void add(int &y,int pos,int l = 1,int r = n){
	if(!y) y = ++cnt; val[y]++; if(l == r) return; int mid = l + r >> 1;
	if(pos <= mid) add(ls[y],pos,l,mid);else add(rs[y],pos,mid+1,r);
}

int query(int y,int pos,int l = 1,int r = n){
	if(l == r) return val[y]; if(!y) return 0; int mid = l + r >> 1;
	if(pos <= mid) return query(ls[y],pos,l,mid);else return query(rs[y],pos,mid+1,r);
}

void dfs1(int x){
	for(int y : G[x]){
		dfs1(y), merge(rt[x],rt[y]);
	}add(rt[x],dep[x]);
	for(pii t : que[x])
		ans[t.fi] = query(rt[x],t.se) - 1;
}

int main (){
#ifndef ONLINE_JUDGE
	freopen("1.in","r",stdin);
#endif
	n = in;
	for(int i = 1;i <= n;i++) {fa[0][i] = in;if(fa[0][i]) G[fa[0][i]].pb(i);}
	for(int i = 1;i <= n;i++) if(!fa[0][i]) dfs(i);
	for(int i = 1;i <= 20;i++)
		for(int j = 1;j <= n;j++)
			fa[i][j] = fa[i-1][fa[i-1][j]];
	m = in;
	for(int i = 1;i <= m;i++){
		int x = in,k = in;
		if(dep[x] <= k) continue;
		que[kanc(x,k)].pb(pii(i,dep[x]));
	}
	for(int i = 1;i <= n;i++) if(!fa[0][i]) dfs1(i);
	for(int i = 1;i <= m;i++) printf("%d%c",ans[i]," \n"[i==m]);
	return 0;
}
